package com.hzyb.shopCart.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzyb.shopCart.dao.ShopCartDao;
import com.hzyb.shopCart.model.ShopCart;
import com.hzyb.shopCart.service.ShopCartService;
import com.hzyb.shopOrderdetail.dao.ShopOrderDetailDao;
import com.hzyb.shopOrderdetail.model.ShopOrderDetail;
@Service("shopCartService")
@Transactional
public class ShopCartServiceImpl implements ShopCartService{

	@Autowired
	private ShopCartDao ShopCartDao;

	@Autowired
	private ShopOrderDetailDao ShopOrderDetailDao;

	@Override
	public Map<String, Object> addShopCart(JSONObject jsonObject) {
		Map<String, Object> map=new HashMap<>();
		String openId=jsonObject.getString("openId");
		String num=jsonObject.getString("num");
		String commoditySid=jsonObject.getString("commoditySid");
		JSONArray jsonArray=jsonObject.getJSONArray("type");
		if(StringUtils.isEmpty(openId)) {
			map.put("status", "fail");
			map.put("error_msg", "openId为空");
		}
		if(StringUtils.isEmpty(num)) {
			map.put("status", "fail");
			map.put("error_msg", "num为空");
		}
		if(StringUtils.isEmpty(commoditySid)) {
			map.put("status", "fail");
			map.put("error_msg", "commoditySid为空");
		}
		ShopCart shopCart=new ShopCart();
		shopCart.setCommoditySid(commoditySid);
		shopCart.setEnterDate(new Date());
		shopCart.setEnterUserid(openId);
		shopCart.setUserid(openId);
		shopCart.setNum(Integer.parseInt(num));
		String shopCartId=ShopCartDao.save(shopCart).getCartSid();
		List<ShopOrderDetail> list=new ArrayList<>();
		for(Object object:jsonArray) {
			ShopOrderDetail shopOrderDetail=new ShopOrderDetail();
			shopOrderDetail.setOrderId(shopCartId);
			JSONObject jsonObject2=JSONObject.parseObject(String.valueOf(object));
			shopOrderDetail.setSpecificationSid(jsonObject2.getString("id"));
			shopOrderDetail.setSpecificationValue(jsonObject2.getString("value"));
			list.add(shopOrderDetail);
		}
		ShopOrderDetailDao.save(list);
		map.put("status", "success");
		return map;
	}

	@Override
	public void numChange(String cartId, String num) {
		// TODO Auto-generated method stub
		ShopCart shopCart=ShopCartDao.findOne(cartId);
		shopCart.setNum(Integer.parseInt(num));
		ShopCartDao.save(shopCart);
	}

}
